iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
0
def __init__(self):

        #: A case-insensitive dictionary of headers to be sent on each
        #: :class:`Request <Request>` sent from this
        #: :class:`Session <Session>`.
        self.headers = default_headers()
        ...
        ...
        #: Event-handling hooks.
        self.hooks = default_hooks()
        ...
        ...
        #: Maximum number of redirects allowed. If the request exceeds this
        #: limit, a :class:`TooManyRedirects` exception is raised.
        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
        #: 30.
        self.max_redirects = DEFAULT_REDIRECT_LIMIT
        ...
        ...
        #: A CookieJar containing all currently outstanding cookies set on this
        #: session. By default it is a
        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
        #: may be any other ``cookielib.CookieJar`` compatible object.
        self.cookies = cookiejar_from_dict({})
        ...
        ...
        # Default connection adapters.
        self.adapters = OrderedDict()
        self.mount('https://', HTTPAdapter())
        self.mount('http://', HTTPAdapter())

Default Headers

預設的header有4個

  • User-Agent: python-requests/[requests version]
  • Accept-Encoding: gzip, deflate
  • Accept: */*
  • Connection: keep-alive

utils.py 中回傳了一個CaseInsensitiveDict,該結構是requests package自己實作,繼承了collections.abc的MutableMapping

def default_headers():
    """
    :rtype: requests.structures.CaseInsensitiveDict
    """
    return CaseInsensitiveDict({
        'User-Agent': default_user_agent(),
        'Accept-Encoding': ', '.join(('gzip', 'deflate')),
        'Accept': '*/*',
        'Connection': 'keep-alive',
    })

Default Hooks

hooks.py中回傳一個dictionary

HOOKS = ['response']


def default_hooks():
    return {event: [] for event in HOOKS}

Cookie

cookies.py 中回傳了一個RequestsCookieJar,該結構是requests package自己實作,繼承了cookielib的CookieJar和collections.abc的MutableMapping,比較好奇的是該結構並沒有放在structures.py

def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
    """Returns a CookieJar from a key/value dictionary.
    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :param cookiejar: (optional) A cookiejar to add the cookies to.
    :param overwrite: (optional) If False, will not replace cookies
        already in the jar with new ones.
    :rtype: CookieJar
    """
    if cookiejar is None:
        cookiejar = RequestsCookieJar()

    if cookie_dict is not None:
        names_from_jar = [cookie.name for cookie in cookiejar]
        for name in cookie_dict:
            if overwrite or (name not in names_from_jar):
                cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))

    return cookiejar

Adapters

prefix有https://http://
self.adapters是一個OrderedDict,最後根據prefix長度呈現遞減排序

def mount(self, prefix, adapter):
        """Registers a connection adapter to a prefix.
        Adapters are sorted in descending order by prefix length.
        """
        self.adapters[prefix] = adapter
        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]

        for key in keys_to_move:
            self.adapters[key] = self.adapters.pop(key)

參考


上一篇
Day6-requests.get
下一篇
Day8-Session-Prepare and Send
系列文
Why it works: python requests and urllib330
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言